#!/usr/bin/env python
#coding:utf-8
"""
  Author:  程勇 --<>
  Purpose: 动脑学院第15节作业
  Created: 2018/3/1
"""

import os
import functools

'''1.range(),需要生成下面的列表,需要填入什么参数:'''
def question_01():
    #[3,4,5,6]
    list_01 = list(range(3,7))
    
    #[3,6,9,12,15,18]
    list_02_1 = list(range(3,19,3))
    list_02_2 = [x * 3 for x in range(1,7)]
    
    #[-20,200,420,640,860]
    list_03_1 = list(range(-20,861,220))
    list_03_2 = [x * 20 for x in range(-1,44,11)]
    
    print('列表显示\n{}\n{}\n{}\n{}\n{}\n'.format(list_01,list_02_1,list_02_2,list_03_1,list_03_2))
    
'''列表推导式或者生成器表达式(2选择1)完成1-100之间所有偶数和'''
def question_02():
    #列表推导式
    print('1-100之间所有偶数和(列表推导式)：',functools.reduce(lambda x,y:x+y,[e for e in range(2,101,2)]))
    
    #生成器
    g_even = (x for x in range(2,101,2))
    sum = 0
    while True:
        try:
            sum += next(g_even)
        except StopIteration as e:
            break
    print('1-100之间所有偶数和（生成器）:',sum)

'''定义一个函数,使用关键字yield创建一个生成器,求1,3,5,7,9各数
   字的三次方,并把所有的结果放入到list里面打印输入'''
def third_power(max):
    n = max
    while n > 0:
        yield n ** 3
        n -= 2
        
def question_03():
    q_03 = third_power(9)

    r_list = []
    while True:
        try:
            r_list.append(next(q_03))
        except StopIteration as e:
            break
        
    print('1,3,5,7,9的三次方',r_list)

'''写一个自定义的迭代器类(iter)'''
class MyIter():
    def __init__(self,min,max,step):
        self.min = min
        self.max = max
        self.step = step
        
    def __next__(self):
        if self.min > self.max:
            raise StopIteration('不必再取数据')
        tem = chr(self.min)
        self.min += self.step
        return tem

    def __iter__(self):
        return self
    
def question_04():
    q_04 = MyIter(97,120,3)
    
    for v in q_04:
        print(v)
        
def main():
    print('第一题')
    question_01()
    
    print('第二题')
    question_02()
    
    print('第三题')
    question_03()
    
    print('第四题')
    question_04()
    
if __name__ == '__main__':
    main()